package com.ibm.spatiotemp.datamodel.config;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

/**
 * 
 * @author xuxiaomin
 * 
 */
public class BackendServerManager {
	public static int DefaultMaxSize = 100;
	public static Logger logger = Logger.getLogger(BackendServerManager.class);
	
	/*for later to support multiple topics*/
	public static ConcurrentHashMap<String, Vector<PubSubMeta>>
	topic2serverMap = new ConcurrentHashMap<String, Vector<PubSubMeta>>();

	public static void init(String configpath){
		LoadfromFile(configpath);
	}
	
	private static void InsertPubSubMeta(String line) {
		PubSubMeta curmeta = new PubSubMeta(line);
		String key = curmeta.getTopic();
		Vector<PubSubMeta> curset = topic2serverMap.get(key);
		/*here, each server only care their own topics*/
		if(curmeta.getServerID().equalsIgnoreCase(com.ibm.spatiotemp.server.config.LocalConfig.INDEXSERVERID)){
		if (curset == null) {
			curset = new Vector<PubSubMeta>(DefaultMaxSize);
			curset.add(curmeta);
		} else {
			curset.add(curmeta);
		}
		}
		topic2serverMap.put(key, curset);
	}

	public static void LoadfromFile(String filepath) {
		BufferedReader freader = null;
		try {
			freader = new BufferedReader(new FileReader(filepath));
			String curline = null;
			while ((curline = freader.readLine()) != null) {
				InsertPubSubMeta(curline);
			}
		} catch (FileNotFoundException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		}
	}
	
	/**
	 * random select a meta from a topic's PubSubMetaVector
	 * @param topic
	 */
	public synchronized static PubSubMeta getPubSubMetaByTopic(String topic){
		Vector<PubSubMeta> curset = 
				topic2serverMap.get(topic);
		if(curset != null && !curset.isEmpty()){
			int size = curset.size();
			Random rand = new Random();
			int idx = rand.nextInt(size);
			return curset.get(idx);
		}
		else
		{
			logger.error("topic not founded : "+ topic);
			return null;
		}
	}
	
	public synchronized static PubSubMeta[] getAllPubSubMetaByTopic(String topic){
		Vector<PubSubMeta> curset = 
				topic2serverMap.get(topic);
		Object[] res = curset.toArray();
		PubSubMeta[] res1 = new PubSubMeta[res.length];
		for (int i = 0; i < res.length; i++) {
			res1[i] = (PubSubMeta)res[i];
		}
		return res1;
	}
	
}
